package br.com.bacabeleireiros.util;

import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpSession;

import br.com.bacabeleireiros.sysbeleza.entity.Usuario;

public class AuthorizationListener implements PhaseListener {

	private static final long serialVersionUID = 1L;
	private Usuario user;
	FacesContext facesContext;

	public void afterPhase(PhaseEvent event) {
		facesContext = event.getFacesContext();
		String currentPage = facesContext.getViewRoot().getViewId();

		boolean isLoginPage = (currentPage.lastIndexOf("login.xhtml") > -1);
		user = (Usuario) ((HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true)).getAttribute("user");

		if (!isLoginPage && user == null) {
			desviaParaLogin();
		}

		@SuppressWarnings("unused")
		Integer tipoColaborador;
//		if (user == null) {
//			tipoColaborador = 0;
//		} else {
//			tipoColaborador = user.getTipocolaborador().getTco_codigo();
//		}


		//bloqueia paginas para o operador
		/*if (tipoColaborador == 3) {
			if (!currentPage.equals("/pages/protected/colaborador.xhtml") &&
				!currentPage.equals("/pages/protected/colaboradorLocalAtuacao.xhtml") &&
				!currentPage.equals("/pages/protected/localatuacao.xhtml")
			   ){
				desviaParaLogin();
			}
		}
		*/

	}
	
	public void desviaParaLogin(){
		((HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true)).invalidate();
		NavigationHandler nh = facesContext.getApplication().getNavigationHandler();
		nh.handleNavigation(facesContext, null, "login");
	}

	public void beforePhase(PhaseEvent event) {
		
	}

	public PhaseId getPhaseId() {
		return PhaseId.RESTORE_VIEW;
	}

}